#!/usr/bin/env -S node -r ./livescript-transform-implicit-async/register

require! <[
  path
  ./git
  ./argv.ls
]>
require! {
  \fs-extra : fs
}


module.exports = !~>
  {cwd, config} = argv
  {template} = config

  update = ~>
    require(\./template.ls)(argv)

  head = path.join cwd, \6du/template.head
  if await fs.exists head
    head = await fs.read-file head, \utf-8
    oid = await git.resolve-ref {
      ref:\HEAD
      dir:template
    }
    if head != oid
      now = await git.read-object {
        dir:template
        oid
      }
      try
        pwd = await git.read-object {
          dir:template
          oid:head
        }
      catch err
        await fs.remove head
        await update!
        return
      if now.object.committer.timestamp > pwd.object.committer.timestamp
        await update!
  else
    await update!


if require.main == module
  do !~>
    await module.exports!

